package useraddress

import (
	"context"

	"mall/service/backend/api/internal/logic/utils"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/i18n"
	"mall/service/user/rpc/userclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserAddressByIdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 通过ID获取UserAddress
func NewGetUserAddressByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserAddressByIdLogic {
	return &GetUserAddressByIdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetUserAddressByIdLogic) GetUserAddressById(req *types.IDReq) (resp *types.UserAddressInfoResp, err error) {
	data, err := l.svcCtx.UserRpc.BackendGetUserAddressById(l.ctx, &userclient.IDReq{
		Id: req.Id,
	})
	if err != nil {
		return nil, err
	}

	var geographic []*types.UserMetaInfo
	if len(data.Geographic) > 0 {
		for _, v := range data.Geographic {
			geographic = append(geographic, &types.UserMetaInfo{
				Uid:   v.Uid,
				Id:    v.Id,
				Key:   v.Key,
				Value: v.Value,
				Label: v.Label,
				Slug:  v.Slug,
			})
		}
	}
	option := utils.GetOptionByStatus(data.Status)
	return &types.UserAddressInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: &types.UserAddressInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:         data.Id,
				CreatedAt:  data.CreatedAt,
				UpdatedAt:  data.UpdatedAt,
				DeletedAt:  data.DeletedAt,
				CanAccept:  option.CanAccept,
				CanReject:  option.CanReject,
				CanRemove:  option.CanRemove,
				CanRestore: option.CanRestore,
			},
			Label:           data.Label,
			UserId:          data.UserId,
			Consignee:       data.Consignee,
			Mobile:          data.Mobile,
			Province:        data.Province,
			City:            data.City,
			District:        data.District,
			Street:          data.Street,
			DetailedAddress: data.DetailedAddress,
			PostalCode:      data.PostalCode,
			RegionCode:      data.RegionCode,
			IsDefault:       data.IsDefault,
			Status:          data.Status,
			LastUsedAt:      data.LastUsedAt,
			Geographic:      geographic,
		},
	}, nil
}
